package gae.colopl.http.request;

import gae.colopl.http.user.Session;
import gae.util.http.client.Cookie;
import gae.util.http.client.Header;
import gae.util.http.client.HttpRequest;
import gae.util.http.client.HttpResponse;
import gae.util.http.client.Parameter;

public class ColoplRequestUtil {

    
    protected Header getDefaultRequestHeader() {
        Header header = new Header();
        header.add("Host", "c.colopl.jp");
        header.add("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; ja; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)");
        header.add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        header.add("Accept-Language", "ja,en-us;q=0.7,en;q=0.3");
        header.add("Accept-Encoding", "Accept-Encoding: gzip,deflate");
        header.add("Accept-Charset", "Shift_JIS,utf-8;q=0.7,*;q=0.7");
        header.add("Keep-Alive", "300");
        header.add("Connection", "keep-alive");
        
        return header;
    }
    
    protected Parameter getDefaultRequestParameter(Session user) {
        Parameter param = new Parameter();
        param.set("id", user.getId());
        param.set("uid", user.getUid());
        param.set("guid", "ON");
        
        return param;
    }
    
    protected Cookie getDefaultRequestCookie(Session user) {
        Cookie cookie = new Cookie();
        cookie.addParam("JSESSIONID", user.getJsessionid(), 0);
        cookie.addParam("pt", user.getPt(), 0);
        cookie.addParam("username", user.getUsername(), 0);
        
        return cookie;
    }
    
    protected HttpRequest getDefaultRequest(String method, String url, Session user) {
        HttpRequest req = new HttpRequest(method, url);
        Header reqHeader = getDefaultRequestHeader();
        reqHeader.setCookie(getDefaultRequestCookie(user));
        req.setHeader(reqHeader);
        req.setParameter(getDefaultRequestParameter(user));
        
        return req;
    }
    
    protected void updateCookie(Session user, HttpResponse res) {
        Header header = res.getHeader();
        Cookie cookie = header.getCookie();
        String jsessionid = cookie.getParam("JSESSIONID");
        if (jsessionid != null) {
            user.setJsessionid(jsessionid);
        }
        String pt = cookie.getParam("pt");
        if (pt != null) {
            user.setPt(pt);
        }
    }
    
}
